package com.auto.learning.activity;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.bean.AppBaseConfig;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.bean.UserVipInfo;
import com.auto.learning.event.BuySuccessEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.PayUtils;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.DateUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.MyToast;
import com.auto.learning.view.PupDingYueDialog;
import com.auto.learning.view.PupPayDialog;
import com.auto.learning.view.PupDingYueDialog.PayUtil;
import com.auto.learning.view.PupPayDialog.OnPayItemClick;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * VIP订阅
 * @author wangjianjun
 */
public class SubscriptionActivity extends BaseActivity {
	public 	static String ACTION_DISMISS="dismiss";
	private TextView tv_sub,tv_vip_sub,tv_count,tv_vip_sub1;
	private LinearLayout rel_main;
	private String yearMoneyYuan;
	

	private Handle handle = new Handle(SubscriptionActivity.this){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
					CommonMethod.makeNotice(SubscriptionActivity.this, "登录成功");
					ResponeResult login_result = (ResponeResult) msg.obj;
					if(login_result != null){
						EventBus.getEventBus("login_success_refreshUI").post(login_result);
					}
					break;
				case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
					CommonMethod.makeNotice(SubscriptionActivity.this, msg.obj.toString());
					break;
				case HttpRequestHelper.GETDATA_SUCCESS:
					ResponeResult result = (ResponeResult) msg.obj;
					if (result != null) {
						try {
							JSONObject jsonObject = new JSONObject(result.getData());
							int yearSum = jsonObject.optInt("buySum", 0);
							yearMoneyYuan	 = jsonObject.optString("yearMoneyYuan", "");
							tv_sub.setText(String.format(getResources().getString(R.string.text_subscription), !TextUtils.isEmpty(yearMoneyYuan) ? "￥"+yearMoneyYuan+"" : "198"));
							tv_vip_sub.setText(String.format(getResources().getString(R.string.text_vie_sub), !TextUtils.isEmpty(yearMoneyYuan) ? yearMoneyYuan.replace("￥", "")+"" : "198"));
							tv_count.setText(String.format(getResources().getString(R.string.text_sub_buy_year_sum), yearSum+""));
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					break;
				case HttpRequestHelper.GETDATA_FAIL:
					if (msg.obj != null) {
						CommonMethod.makeNotice(SubscriptionActivity.this, msg.obj.toString());
					}
					break;
				case HttpRequestHelper.BUY_BOOK_SUCCESS:
					ResponeResult buyResult = (ResponeResult)msg.obj;
					
					 switch (buyResult.getCode()) {
					 
					case 0:
						UserVipInfo userVipInfo = new Gson().fromJson(buyResult.getData(), new TypeToken<UserVipInfo>() {}.getType());
						 MyUserInfo.getInstance().getUserInfoBean().setVipInfo(userVipInfo);
						 String sql = " update book set needBuy = 1 ";
						 try {
								StaticReference.mutilDBSupport.getDao(BookBean.class).queryRaw(sql);
							} catch (SQLException e) {
								e.printStackTrace();
							}
						 EventBus.getEventBus("m_buy_success").post(new BuySuccessEvent(0));
						 new MyToast(SubscriptionActivity.this, "订阅成功","您已成功订阅路上读书Vip有效时间："+CommonMethod.formDate(userVipInfo.getVipExpired())+"" );
						 Intent intent=new Intent();
						 intent.setAction(SubscriptionActivity.ACTION_DISMISS);
						 sendBroadcast(intent);
						break;
					case -203:
						PupDingYueDialog dialog=new PupDingYueDialog(SubscriptionActivity.this);
						dialog.setPayOnClick(new PayUtil() {
							
							@Override
							public void setpay() {
								//判断余额是否大于198
								int money=198;
								if(TextUtils.isEmpty(yearMoneyYuan)){
									money=Integer.parseInt(yearMoneyYuan);
								}
								PupPayDialog pup_Pay_Dialog = new PupPayDialog(SubscriptionActivity.this, money);
								pup_Pay_Dialog.setOnPayItemClick(new OnPayItemClick() {
										
										@Override
									public void onWechatPayClick(int money) {
											TemporaryVariable.bookmoney.setType(3);
										new PayUtils(SubscriptionActivity.this, 2, money * 100).pay();
									}
										
									@Override
									public void onAliPayClick(int money) {
										TemporaryVariable.bookmoney.setType(3);
										new PayUtils(SubscriptionActivity.this, 1, money * 100).pay();
									}
								});
									pup_Pay_Dialog.show(tv_sub);
								}
								
								
							
						});
						dialog.show(tv_sub);
						break;
					default:
						break;
					}
					break;
				case  HttpRequestHelper.BUY_BOOK_FAIL:
					if (msg.obj != null) {
						CommonMethod.makeNotice(SubscriptionActivity.this, msg.obj+"");
					}
					break;
			}
		};
	};
	 
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setViewInLine(R.layout.subscription_activity);
		
		IntentFilter filter=new IntentFilter();
		filter.addAction(ACTION_DISMISS);

		initView();
		getData();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		TemporaryVariable.bookmoney.setType(0);
		super.onDestroy();
	}
	
	

	private void initView(){
		setTitle("VIP订阅");
		rel_main = (LinearLayout) findViewById(R.id.rel_main);
		rel_main.setBackgroundColor(getResources().getColor(R.color.black));
		tv_sub = (TextView) findViewById(R.id.tv_sub);
		tv_vip_sub1=(TextView) findViewById(R.id.tv_vip_sub1);
		tv_count = (TextView) findViewById(R.id.tv_count);
		tv_vip_sub = (TextView) findViewById(R.id.tv_vip_sub);
		AppBaseConfig config = MyUserInfo.getInstance().getUserInfoBean().getConfig();
		tv_sub.setText(String.format(getResources().getString(R.string.text_subscription), config != null ? config.getYearMoneyYuan()+"" : "198"));
		tv_vip_sub1.setText(String.format(getResources().getString(R.string.text_vip_dyxz_body), config != null ? config.getYearMoneyYuan()+"" : "198"));
		tv_vip_sub.setText(String.format(getResources().getString(R.string.text_vie_sub), config != null ? config.getYearMoneyYuan().replace("￥", "")+"" : "198"));
		tv_sub.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (CommonMethod.checkUserLogin(SubscriptionActivity.this, getResources().getString(R.string.text_sub_bef_login))) {
					HttpRequestHelper.buy(SubscriptionActivity.this, handle, 0 , HttpRequestHelper.BUY_BOOK_SUCCESS, HttpRequestHelper.BUY_BOOK_FAIL);
					
				}
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(SubscriptionActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"), data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handle);
				}
			});
		}else if (requestCode == 100 && resultCode == 204) {
			EventBus.getEventBus("login_refreshUI").post(new LoginSuccessEvent());
		}
	}
	
	public void getData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.PAY_BUY_YEAR_SUM, params, handle,HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}

}
